#include "soc_timer.h"
#include "soc_misc.h"

uint16_t m_timerH[] = {0, 0, 0};
uint16_t m_timerL[] = {0, 0, 0};

void SOC_TimerInit(SOC_TimerNo_t no, uint32_t us)
{
	SOC_TimerSetTimeOut(no, us);

	switch(no)
	{
		case S_TIMER_0:
		ET0 = 1;
		TMOD |= 0X01;
		break;
		case S_TIMER_1:
		ET1 = 1;
		TMOD |= (0X01 << 4);
		break;
		case S_TIMER_2:
		ET2 = 1;
		T2CON = 0x00;
		C_T2 = 0;
		CP_RL2 = 0;
		EXEN2 = 0;	
		break;
		default:
		break;
	}
}

void SOC_TimerSetTimeOut(SOC_TimerNo_t no, uint32_t us)
{
	uint16_t count = (uint16_t)(us / (12000000.0 / SOC_GetCpuFrequency()) + 0.5);

	m_timerH[no] = (65536-count)>>8;
	m_timerL[no] = 65536-count; 
	switch(no)
	{
		case S_TIMER_0:
        TH0 = m_timerH[no];
        TL0 = m_timerL[no]; 
        break;
        case S_TIMER_1:
        TH1 = m_timerH[no];
        TL1 = m_timerL[no];
        break;
		case S_TIMER_2:
		TH2 = m_timerH[no];
		TL2 = m_timerL[no];
		RCAP2L = m_timerH[no];		//设置定时重载值
		RCAP2H = m_timerL[no]; //0x3C;		//设置定时重载值
		break;
        default:
        break;
	}
}

void SOC_TimerReload(SOC_TimerNo_t no) 
{
	switch(no)
	{
		case S_TIMER_0:
        TH0 = m_timerH[no];
        TL0 = m_timerL[no]; 
        break;
        case S_TIMER_1:
        TH1 = m_timerH[no];
        TL1 = m_timerL[no];
        break;
		case S_TIMER_2:
		break;
        default:
        break;
	}
}

void SOC_TimerStart(SOC_TimerNo_t no)
{
	switch(no)
	{
		case S_TIMER_0:
		TR0 = 1;
		break;
		case S_TIMER_1:
		TR1 = 1;
		break;
		case S_TIMER_2:
		TR2 = 1;
		break;
		default:
		break;
	}
}

void SOC_TimerStop(SOC_TimerNo_t no)
{
	switch(no)
	{
		case S_TIMER_0:
		TR0 = 0;
		break;
		case S_TIMER_1:
		TR1 = 0;
		break;
		case S_TIMER_2:
		TR2 = 0;
		break;
		default:
		break;
	}
}

uint16_t SOC_TimerGetCounter(SOC_TimerNo_t no)
{
	uint16_t count = 0;

	switch(no)
	{
		case S_TIMER_0:
		count = (TH0 << 8) | TL0;
		break;
		case S_TIMER_1:
		count = (TH1 << 8) | TL1;
		break;
		case S_TIMER_2:
		count = (TH2 << 8) | TL2;
		break;
		default:
		break;
	}

	return count;
}

void SOC_TimerInitCountMode(SOC_TimerNo_t no)
{
	switch(no)
	{
		case S_TIMER_0:
		ET0 = 0;
		TMOD |= 0X05;
		break;
		case S_TIMER_1:
		ET1 = 0;
		TMOD |= (0X05 << 4);
		break;
		case S_TIMER_2:
		ET2 = 0;
		T2CON = 0x00;
		C_T2 = 1;
		CP_RL2 = 0;
		EXEN2 = 0;	
		break;
		default:
		break;
	}
}
